// pages/address/add/add.js
import {
  saveAddressApi,
  updateAddressApi,
  getAddressByIdApi,
} from "../../../api/address";

Page({
  /**
   * 页面的初始数据
   */
  data: {
    show: false,
    // 姓名
    name: "",
    // 电话
    phone: "",
    // 标签
    tagName: "家",
    // 用户地址
    address: "",
    // 省
    provinceCode: "",
    // 市
    cityCode: "",
    // 区
    districtCode: "",
    // 是否是默认地址
    isDefault: 0,
    // 用户选择地址 省/市/县
    region: "",
    // 地址id，用于修改地址跳转过来的地址id
    id: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    const { id } = options;
    if (id) {
      const {
        name,
        phone,
        provinceCode,
        provinceName,
        cityCode,
        cityName,
        districtCode,
        districtName,
        tagName,
        isDefault,
        address,
      } = await getAddressByIdApi(id);
      this.setData({
        id,
        name,
        phone,
        provinceCode,
        cityCode,
        districtCode,
        region: provinceName + "/" + cityName + "/" + districtName,
        tagName,
        isDefault,
        address,
      });
    }
  },

  handleRegionChange(e) {
    const { code, value } = e.detail;
    this.setData({
      region: value.join("/"),
      provinceCode: code[0],
      cityCode: code[1],
      districtCode: code[2],
    });
  },

  handleSwitchChange(e) {
    const isDefault = e.detail ? 1 : 0;
    this.setData({
      isDefault,
    });
  },

  async saveAddress() {
    const {
      id,
      name,
      phone,
      provinceCode,
      cityCode,
      districtCode,
      address,
      tagName,
      isDefault,
    } = this.data;

    const data = {
      name,
      phone,
      provinceCode,
      cityCode,
      districtCode,
      address,
      tagName,
      isDefault,
    };

    if (id) {
      updateAddressApi({
        ...data,
        id,
      });
    } else {
      await saveAddressApi(data);
    }

    wx.showToast({
      title: `${id ? "修改" : "添加"}地址成功`,
      icon: "none",
    });
    wx.navigateBack({
      delta: 1,
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
});
